<?php

namespace Hilaoyu\SoftetherJsonrpcClient;

use Hilaoyu\SoftetherJsonrpcClient\Api\HubApi;
use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilHttp;
use Hilaoyu\Utils\UtilStr;

/**
 * Class SoftetherJsonrpcClient
 * @package Hilaoyu\SoftetherJsonrpcClient
 * @property UtilHttp $client
 */
class SoftetherJsonrpcClient
{

    use ErrorsTrait;
    protected $client;
    protected $hub_api;

    static public function make($host, $port, $password, $hubName = '')
    {
        return new static($host, $port, $password, $hubName);
    }

    public function __construct($host, $port, $password, $hubName = '')
    {

        $client = new UtilHttp("https://" . $host . ":" . $port . '/api', 'post');
        $client->setGlobalHeaders([
            'X-VPNADMIN-HUBNAME' => $hubName,
            'X-VPNADMIN-PASSWORD' => $password,
        ]);

        $this->client = $client;
    }

    public function useProxySockes5($host, $port = 1080, $user = '', $password = ''){
        $this->client->useProxySocks5($host, $port, $user, $password);
        return $this;
    }

    public function request($method,$params = [])
    {
        if(empty($params)){
            $params = new \stdClass();
        }
        $jsonData = [
            "jsonrpc" => "2.0",
            "id" => UtilStr::randString(6),
            "method" => $method,
            "params" => $params
        ];

        $result = $this->client->httpRequestJson('',json_encode($jsonData));
        //dump($result);
        if(!$result){
            $this->setError($this->client->getError());
            return null;
        }

        $error = UtilArr::get($result,'error');

        if(!empty($error)){
            $this->setError(UtilArr::get($error,'message'));
            return null;
        }

        return UtilArr::get($result,'result');
    }


    public function test(){
        return (bool)$this->request('Test',['IntValue_u32'=>0]);
    }


    public function hubApi(){
        if(!$this->hub_api instanceof HubApi){
            $this->hub_api = new HubApi($this);
        }
        return $this->hub_api;
    }


    static public function CreateUserPasswordHash($username, $password){



        $hashCreator = new SHA0();
        $hashCreator->Update(unpack('C*', $password));
        $hashCreator->Update(unpack('C*', strtoupper($username)));
        $hashedPw = $hashCreator->ToBase64();
        return $hashedPw;
    }


    static public function BinToStr($content){
        $str = "";
        $bin = base64_decode($content);
        if($bin){
            for ($i = 0;$i<strlen($bin);$i++){
                $str .= dechex(ord($bin[$i]));
            }
        }

        return $str;
    }

    static public function FormatMacAddress($str){
        $str = str_replace(['-',':',' '],'',$str);
        $str = preg_replace('~^(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})(.*)$~','$1:$2:$3:$4:$5:$6',$str);
        return      strtoupper($str);
    }

}
